package com.mes.check.manager;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.mes.basicdata.dao.iface.IDeptDao;
import com.mes.basicdata.domain.Dept;
import com.mes.check.dao.iface.ICertificateDao;
import com.mes.check.domain.Certificate;
import com.mes.check.manager.iface.ICertificateManager;
import com.mes.code.domain.ApplyCodeContent;
import com.mes.code.domain.CodeResult;
import com.mes.code.manager.iface.ICodeRuleManager;
import com.mes.common.exception.bo.BaseBusinessException;
import com.mes.common.manager.BasicManager;
import com.mes.common.spring.SpringUtils;
import com.mes.common.util.CodeUtil;
import com.mes.common.util.IdentityGenerator;
import com.mes.common.util.SysUtil;
import com.mes.task.manager.iface.IPartTaskManager;

public class CertificateManager extends BasicManager<Certificate> implements ICertificateManager {
	private final static Log log = LogFactory.getLog(CertificateManager.class);

	@Autowired
	private SysUtil sysUtil;
	@Autowired
	private CodeUtil codeUtil;
	@Autowired
	private ICodeRuleManager codeRuleManager;
	@Autowired
	private IPartTaskManager partTaskManager;
	@Autowired
	private IDeptDao deptDao;
	@Autowired
	private ICertificateDao certificateDao;

	private boolean isDupId(String certificateId) {
		try {
			boolean isDupId;
			List<Certificate> cl = this.certificateDao.getCertificatesById(certificateId);
			if (cl != null && cl.size() > 0)
				return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public void add(Certificate object) throws Exception {
		Certificate certificate = (Certificate) object;
		if (certificate.getCheckTime() == null)
			certificate.setCheckTime(new Date());
		// 添加时自动设置为有效
		certificate.setCertificateState(10);

		if (certificate.getUuid() == null || certificate.getUuid().length() == 0)
			certificate.setUuid(IdentityGenerator.GetIdentityString());
		if (certificate.getCertificateType().equals("101")) {
			if (certificate.getCertificateId() == null || certificate.getCertificateId().length() == 0) {
				// 合格证编码
//				certificate.setCertificateId(this.generateCode(certificate));
				Dept dept = deptDao.getById(certificate.getDeptUid());
				certificate.setCertificateId(codeUtil.getCertificateBillNumber(dept.getCustomerDeptId()));
			}
		} else if (certificate.getCertificateType().equals("102")) // 返修品合格证
		{
			certificate.setCertificateId(this.generateFXCode(certificate));
		}
		// 严格保证合格证编码不能重复
		if (this.isDupId(certificate.getCertificateId()))
			throw new BaseBusinessException("合格证编码出现重复！" + certificate.getCertificateId());
		super.add(object);

		/**
		 * lqm todo 设计更稳定的日志定时处理模式 设置零件任务状态和指令状态，应该考虑将这一部分参数化
		 * 有时会影响合格证打印，应该将其多线程事件化处理
		 */
		try {
			if (certificate.getTaskUid() != null && certificate.getCertificateType().equals("101"))
				partTaskManager.finishPartTask(certificate.getTaskUid());
			// 是否需要完工入库后再冲销指令
			String propertyName = "needProductInWarehouseDept";
			if (!sysUtil.isDeptExist(certificate.getDeptUid(), propertyName)) {
				partTaskManager.delivery(certificate.getTaskUid(), certificate.getCertificateQty());
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error(e);
			// e.printStackTrace();
		}
		return;
	}

	/**
	 * 生成返修合格证新编码
	 * 
	 * @param certificate
	 * @return
	 * @throws Exception 
	 */
	@SuppressWarnings("unchecked")
	private synchronized String generateFXCode(Certificate certificate) throws Exception {

		String codenumber = codeUtil.getFXCertificateBillNumber(certificate.getCertificateId());
//		String codenumber = codeRuleManager.generateCode("fxhgz", certificate, false);
		if (codenumber == null || codenumber.length() == 0)
			throw new BaseBusinessException("无法生成返修合格证编码！");

		log.info("--%%%%%%%%%%%--codenumber%%%%%%%%%%%%%%%@---------返修合格证编码为：" + codenumber);
		return codenumber;

	}

//	/**
//	 * 生成新编码
//	 * 
//	 * @param certificate
//	 * @return
//	 * @throws BaseBusinessException
//	 */
//	@SuppressWarnings("unchecked")
//	private synchronized String generateCode(Certificate certificate) throws BaseBusinessException {
//		try {
//			String codenumber = "";
//
//			List<String> features = new ArrayList<String>();
//			ApplyCodeContent applyCodeContent = new ApplyCodeContent();
//			// applyCodeContent.setApplyCodeId(codeRuleUid);
//			// applyCodeContent.setClassUid(codeRuleUid);
//			applyCodeContent.setCustomerClassId("hgz");
//			applyCodeContent.setUniqueCheck(false);
//			if (certificate.getDeptUid() == null || certificate.getDeptUid().length() == 0)
//				throw new BaseBusinessException("无法生成合格证编码！主制部门编码不能为空");
//			Dept dept = (Dept) deptDao.getById(certificate.getDeptUid());
//			if (dept == null || dept.getCustomerDeptId() == null)
//				throw new BaseBusinessException("无法生成合格证编码！无法找到主制部门的编码简称！");
//			features.add("bm=" + dept.getCustomerDeptId());
//
//			// if (certificate.getCheckTime() == null)
//			// throw new BaseBusinessException("无法生成合格证编码！检验日期不能为空");
//			// SimpleDateFormat formatDate = new SimpleDateFormat("yyMM");
//			// features.add("yymm=" +
//			// formatDate.format(certificate.getCheckTime()));
//			//
//			// features.add("hgzwyh=" + certificate.getCertificateUid());
//			//
//
//			applyCodeContent.setFeatures(features);
//			boolean iExists = false;
//			do {
//				CodeResult codeResult = codeRuleManager.generateCode(applyCodeContent);
//				iExists = false;
//				if (codeResult != null) {
//					codenumber = codeResult.getGeneratedCode();
//					try {
//						if (this.isDupId(codenumber)) {
//							iExists = true;
//							log.warn("合格证号出现重复，自动申请下一个合格证号！");
//						} else
//							break;
//					} catch (Exception e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//						throw new BaseBusinessException(e.getMessage());
//					}
//				}
//			} while (iExists);
//			log.info("--%%%%%%%%%%%--codenumber%%%%%%%%%%%%%%%@---------合格证编码为：" + codenumber);
//			return codenumber;
//		} catch (RuntimeException e) {
//			// TODO Auto-generated catch block
//			throw new BaseBusinessException("无法生成合格证编码！");
//		}
//	}

	@Override
	public void printCerticate(String certificateUid) throws Exception {
		// TODO Auto-generated method stub
		Certificate certificate = (Certificate) this.getById(certificateUid);
		certificate.setLastPrintTime(new Date());
		this.update(certificate);
	}

}
